<template>
  <div id="person-view">
    <div class="person-info">
      <div class="info-content">
        <h2>个人信息</h2>
        <el-button
          type="text"
          size="small"
          :icon="isEdit? 'el-icon-check' : 'el-icon-edit'"
          @click="onSubmit(1)"
        >
          {{ isEdit? '提交' : '编辑' }}
        </el-button>
      </div>
      <el-form ref="personRef" :model="personForm" :rules="personRules" label-width="100px" size="small">
        <el-form-item label="用户昵称：" prop="nickName">
          <span v-if="!isEdit">{{ personForm.nickName }}</span>
          <el-input
            v-else
            v-model="personForm.nickName"
            placeholder="请输入用户昵称"
            prefix-icon="iconfont icon-nicheng"
          />
        </el-form-item>
        <el-form-item label="头像：">
          <el-image
            style="width: 100px; height: 100px"
            :src="avatarUrl"
            :preview-src-list="[avatarUrl]"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
          <RbUpload
            v-if="isEdit"
            ref="upload"
            style="float: right;"
            :file-list="fileList"
            :show-file-list="false"
            tip="建议长宽1:1，支持JPG、PNG、JPEG格式，小于500KB。"
            button-type="text"
            accept=".jpg,.jpeg,.png,.gif,.bmp"
            @on-success="handleUploadSuccess"
          />
        </el-form-item>
        <el-form-item label="邮箱地址：" prop="email">
          <span v-if="!isEdit">{{ personForm.email }}</span>
          <el-input
            v-else
            v-model="personForm.email"
            placeholder="请输入邮箱地址"
            prefix-icon="iconfont icon-youxiang"
          />
        </el-form-item>
      </el-form>
    </div>
    <el-divider />
    <div class="update-password">
      <h2>修改密码</h2>
      <el-form ref="passwordRef" :model="passwordForm" :rules="passwordRules" label-width="100px" size="mini">
        <el-form-item label="原始密码：" prop="originPass">
          <el-input
            v-model="passwordForm.originPass"
            placeholder="请输入密码"
            show-password
            prefix-icon="iconfont icon-mima"
          />
        </el-form-item>
        <el-form-item label="新密码：" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            placeholder="请输入密码"
            show-password
            prefix-icon="iconfont icon-mima"
          />
        </el-form-item>
        <el-form-item label="确认密码：" prop="confirmPass">
          <el-input
            v-model="passwordForm.confirmPass"
            placeholder="请输入密码"
            show-password
            prefix-icon="iconfont icon-mima"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit(2)">提交</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import RbUpload from '@/layout/components/RbUpload.vue'
import { mapGetters } from 'vuex'
import { updateUser } from '@/api/user'

export default {
  name: 'PersonView',
  components: { RbUpload },
  data() {
    return {
      personForm: {
        nickName: '',
        avatar: '',
        email: ''
      },
      passwordForm: {
        originPass: '',
        newPassword: '',
        confirmPass: ''
      },
      isEdit: false,
      fileList: [],
      personRules: {
        email: [{
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (value && !/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value)) {
              return callback(new Error('邮箱格式不正确'))
            }
            return callback()
          }
        }]
      },
      passwordRules: {
        originPass: [{
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            console.log(this.userInfo)
            if (value && value !== this.userInfo.password) {
              return callback(new Error('原始密码不正确'))
            }
            return callback()
          }
        }],
        newPassword: [{ required: true, trigger: 'blur', message: '新密码不能为空' }],
        confirmPass: [{
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (value && this.passwordForm.newPassword !== value) {
              return callback(new Error('两次输入的密码不一致'))
            }
            return callback()
          }
        }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    avatarUrl() {
      return process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API + this.personForm.avatar : this.personForm.avatar
    }
  },
  watch: {
    userInfo: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.personForm = newVal
        }
      }
    }
  },
  methods: {
    onReset() {
      this.$refs.passwordRef.resetFields()
    },

    handleUploadSuccess(buildFile) {
      let fileName = buildFile.fileName
      fileName = fileName.lastIndexOf('.') !== -1 ? fileName : fileName + '.' + buildFile.suffix
      const imgUrl = buildFile.filePath + '/' + fileName
      this.$set(this.personForm, 'avatar', imgUrl)
      this.$refs.upload.$refs.rbUploadRef.clearFiles()
    },

    onSubmit(flag) {
      if (flag === 1) {
        this.isEdit = !this.isEdit
        if (!this.isEdit) {
          this.submitUserUp(flag)
        }
        return
      }
      this.submitUserUp(flag)
    },

    submitUserUp(flag) {
      const refName = flag === 1 ? 'personRef' : 'passwordRef'
      this.$refs[refName].validate((valid) => {
        if (!valid) {
          return false
        }
        const reqUserInfo = { ...this.userInfo }
        reqUserInfo['dataFrom'] = 2
        reqUserInfo['isDelete'] = false
        if (flag === 2) {
          reqUserInfo['password'] = this.passwordForm.confirmPass
        } else {
          reqUserInfo['nickName'] = this.personForm.nickName
          reqUserInfo['avatar'] = this.personForm.avatar
          reqUserInfo['email'] = this.personForm.email
        }
        updateUser(reqUserInfo).then(async res => {
          this.$message.success('操作成功')
          if (flag === 1) {
            // 修改基础信息需要刷新下
            await this.$store.dispatch('user/getInfo')
            location.reload()
            return
          }
          // 修改密码成功，需要重新登录
          this.$confirm('密码修改成功，您可以取消留在此页面上，或重新登录', '确认退出登录', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        }).catch(err => {
          console.error(err)
          this.$message.error('操作失败')
        })
      })
    }
  }
}
</script>

<style scoped>
#person-view {
  padding: 20px;
  width: 600px;
  margin-left: 50px;
}

.person-info .info-content {
  display: flex;
  gap: 20px;
}

.person-info .info-content /deep/ button span {
  font-size: 14px !important;
}
</style>
